package com.activity.shop;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.activity.adapter.AddressChooseAdapter;
import com.activity.bean.AddressBean;
import com.activity.bean.PoiItemBean;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.autonavi.amap.mapcore.Inner_3dMap_location;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.example.apple.ddhr_new.utils.ToastUtil;
import com.example.lzbase.BaseViewModelActivity;
import com.google.gson.Gson;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.function.LongFunction;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

public class AddressChooseActivity extends BaseViewModelActivity {


    @BindView(R.id.tv_search_bar)
    EditText tvSearchBar;
    @BindView(R.id.map)
    MapView mMapView;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    private AddressChooseAdapter addressChooseAdapter;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private AMapLocationListener mlocationListener;

    private PoiSearch poiSearch;
    private PoiSearch.Query query;
    private PoiSearch poiSearch1;
    private PoiSearch.Query query1;

    @Override
    protected int titleText() {
        return R.string.tianjia_kaoqin_didian;
    }

    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        super.created(savedInstanceState);
        tvSearchBar.setImeOptions(EditorInfo.IME_ACTION_DONE);
        tvSearchBar.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null && KeyEvent.KEYCODE_ENTER == keyCode && KeyEvent.ACTION_DOWN == event.getAction()) {
                    // 此处来点freestyle~
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//隐藏软键盘 //
                    imm.hideSoftInputFromWindow(tvSearchBar.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
        addressChooseAdapter = new AddressChooseAdapter(this);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(addressChooseAdapter);
        addressChooseAdapter.notifyDataChanged();
        setTitleRight(getString(R.string.sure));
        mMapView.onCreate(savedInstanceState);
        checkLocation(new LocationPermissionListener() {
            @Override
            public void hasLocationPermission() {
                mMapView.getMap().setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
                mMapView.getMap().setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
                    @Override
                    public void onMyLocationChange(Location location) {

                        Inner_3dMap_location ls =null;
                        if(location instanceof  Inner_3dMap_location ){
                            ls = (Inner_3dMap_location) location;

                        }


                        if(ls!=null&&ls.getErrorCode()==0){
                            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(location.getLatitude(),
                                    location.getLongitude()), 1000));//设置周边搜索的中心点以及半径
                            poiSearch.searchPOIAsyn();
                        }

                    }
                });
            }
        });
        mlocationListener =new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null
                        &&aMapLocation.getErrorCode() == 0) {
                    mlocationListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                } else {

                }
            }
        };

        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        myLocationStyle.showMyLocation(true);

        mMapView.getMap().moveCamera( CameraUpdateFactory.zoomTo(17));
        mMapView.getMap().setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。

        query = new PoiSearch.Query("", "", "");
//keyWord表示搜索字符串，
//第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
//cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);//设置查询页码
        poiSearch = new PoiSearch(this,query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                ArrayList<PoiItemBean> arrayList = new ArrayList<>();
                for(int j=0;j<poiResult.getPois().size();j++){

                    PoiItemBean poiItemBean = new PoiItemBean();
                    poiItemBean.poiItem = poiResult.getPois().get(j);
                    arrayList.add(poiItemBean);
                }
                addressChooseAdapter.getData().clear();
                addressChooseAdapter.getData().addAll(arrayList);
                addressChooseAdapter.notifyDataChanged();

            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {
                PoiItemBean poiItemBean = new PoiItemBean();
                poiItemBean.poiItem = poiItem;
                addressChooseAdapter.getData().clear();
                addressChooseAdapter.getData().add(poiItemBean);
                addressChooseAdapter.notifyDataChanged();
            }
        });


        tvSearchBar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                    if(StringUtils.isEmpty(tvSearchBar.getText().toString()))
                    return;

                 query1 = new PoiSearch.Query(tvSearchBar.getText().toString(), "", "");
//keyWord表示搜索字符串，
//第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
//cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
                query1.setPageSize(20);// 设置每页最多返回多少条poiitem
                query1.setPageNum(0);//设置查询页码
                poiSearch1 = new PoiSearch(AddressChooseActivity.this, query1);
                poiSearch1.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                    @Override
                    public void onPoiSearched(PoiResult poiResult, int i) {

                        ArrayList<PoiItemBean> arrayList = new ArrayList<>();
                        for(int j=0;j<poiResult.getPois().size();j++){

                            PoiItemBean poiItemBean = new PoiItemBean();
                            poiItemBean.poiItem = poiResult.getPois().get(j);
                            arrayList.add(poiItemBean);
                        }
                        addressChooseAdapter.getData().clear();
                        addressChooseAdapter.getData().addAll(arrayList);
                        addressChooseAdapter.notifyDataChanged();

                    }

                    @Override
                    public void onPoiItemSearched(PoiItem poiItem, int i) {

                        PoiItemBean poiItemBean = new PoiItemBean();
                        poiItemBean.poiItem = poiItem;
                        addressChooseAdapter.getData().clear();
                        addressChooseAdapter.getData().add(poiItemBean);
                        addressChooseAdapter.notifyDataChanged();

                    }
                });
                poiSearch1.searchPOIAsyn();


            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });

        addressChooseAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {


                for(int i=0;i<addressChooseAdapter.getData().size();i++){
                    addressChooseAdapter.getData().get(i).selected=false;
                }
                addressChooseAdapter.getData().get(childPosition).selected = true ;
                addressChooseAdapter.notifyDataChanged();

            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_address;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }

        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图

    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图

    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();

        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态

    }

    @Override
    protected void titleRightClick() {

        AddressBean bean= new AddressBean();
        for ( int i=0;i<addressChooseAdapter.getData().size();i++)
        {
            if(addressChooseAdapter.getData().get(i).selected){
                bean.address.add(addressChooseAdapter.getData().get(i).poiItem);
            }

        }
        if(bean.address.size()==0)
        {
            ToastUtil.toast(this,"请选择考勤地址");
        }else
        {

                Intent intent = new Intent();


                Gson gson =new Gson();
                intent.putExtra("data",gson.toJson(bean));


            setResult(100,intent);
            finish();

        }
    }
}
